var map = null,
	layer,
	layer_path,
	layer_path_animator,
	picLayer;
var Map = {};

function IsPC() {
    var userAgentInfo = navigator.userAgent;
    var Agents = ["Android", "iPhone",
                "SymbianOS", "Windows Phone",
                "iPad", "iPod"];
    var flag = true;
    for (var v = 0; v < Agents.length; v++) {
        if (userAgentInfo.indexOf(Agents[v]) > 0) {
            flag = false;
            break;
        }
    }
    return flag;
}
var isPC = IsPC();

var styleCar1 = {
	externalGraphic : "css/imgs/online-0.png",
	allowRotate : true,
	graphicWidth : 32,
	graphicHeight : 32
}

$(function() {
	Map.init();
})

Map.init = function() {
	map = new SuperMap.Map("map", {
		controls : [ new SuperMap.Control.ScaleLine(),
			new SuperMap.Control.Zoom(), new SuperMap.Control.Navigation({
				dragPanOptions : {
					enableKinetic : true
				}
			}) ],
		units : "m"
	});
	// layer = new SuperMap.Layer.CloudLayer();
	layer = new SuperMap.Layer.CloudLayer({
		url : "http://t2.supermapcloud.com/FileService/image"
	});
	layer_path = new SuperMap.Layer.Vector();
	// 初始化汽车图层。
	layer_path_animator = new SuperMap.Layer.AnimatorVector("Cars", {

	}, {
		// 设置速度为每帧播放0.05小时的数据
		speed : 0.1,
		// 开始时间为0晨
		startTime : 0,
		// 结束时间设置为最后运行结束的汽车结束时间
		// endTime:55,
		repeat : false
	});
	picLayer = new SuperMap.Layer.Markers("Pic Layer");
	map.addLayers([ layer, layer_path, layer_path_animator, picLayer ]);
	map.setCenter(new SuperMap.LonLat(11584493.820190, 3589061.070760), 5);

	var url = location.href;
	var t;
	if(url.indexOf("day=") != -1){
		var s = url.substring(url.indexOf("day=") + "day=".length);
		if(s.indexOf("&") != -1){
			s = s.substring(0, s.indexOf("&"));
		}
		t = s;
	}else{
		var d = new Date();
		t = getDay(d);
	}
	document.getElementById("second_car_path_time_star").value = t;
	document.getElementById("second_car_path_time_end").value = t;

	if(url.indexOf("id=") == -1){
		// 没有传参数id时，才自动根据默认值搜索
		getGPS();
	}
}

Map.searchPath = function(data) {
	if(data == "NoData"){
		alert("当天没有数据");
	}
	// alert("data=" + data);
	var arr = data.split("^^");
	var len = arr.length,
		path = [],
		cars = [];
	// alert("len=" + len);
	for (var i = 0; i < len; i++) {
		if (arr[i].indexOf("^") != -1) {
			var arr2 = arr[i].split("^");
			var date = arr2[0];
			var gpsinfos = arr2[1];
			var arr3 = gpsinfos.split("__");
			// alert("len3=" + arr3.length);
			var lastGPSPoint = null;
			for (var j = 0; j < arr3.length; j++) {
				// alert(gpsinfo);
				// 李玮顾,null,,2016-12-22
				// 10:12:15,,104.069180,30.537040,104.069180,30.537040,0,0.0,120.0,null,900,0,0.0,0.0
				var gpsinfo = arr3[j];
				var fileds = gpsinfo.split(",");
				var acoundId = fileds[0];
				var loginMobile = fileds[1];
				var address = fileds[2];
				var gpsTime = fileds[3];
				var uploadTime = fileds[4];
				var x = fileds[5];
				var y = fileds[6];
				var x2 = fileds[7];
				var y2 = fileds[8];
				var gpsTag = fileds[9];
				var speed = fileds[10];
				var speedLimit = fileds[11];
				var plateNumber = fileds[12];
				var status = fileds[13];
				var accuracy = fileds[14];
				var direction = fileds[15];
				var deleteTag = fileds[16];

				var speed = 0;
				if (lastGPSPoint != null) {
					speed = caculateSpeed(lastGPSPoint.x, lastGPSPoint.y, lastGPSPoint.gpsTime, x, y, gpsTime);
				}

				var startTime = document
					.getElementById("second_car_path_time_star").value;
				var endTime = document
					.getElementById("second_car_path_time_end").value;
				//var isValid = (accuracy > 0 && (gpsTime.indexOf(startTime) != -1 || gpsTime.indexOf(endTime) != -1));
				var isValid = (accuracy > 0) && (speed < 125);
				if (isValid) {
					if (acoundId == "李玮顾" && gpsTime.indexOf("2017-02-11") != -1) {
						var curTime = new Date(gpsTime);
						var compareTime = new Date("2017-02-11 15:00:00");
						if (curTime.getTime() > compareTime.getTime()) {
							isValid = false;
						}
					} else if (acoundId == "李玮顾" && gpsTime.indexOf("2017-02-12") != -1) {
						var curTime = new Date(gpsTime);
						var compareTime = new Date("2017-02-12 18:45:00");
						if (curTime.getTime() > compareTime.getTime()) {
							isValid = false;
						}
					}
				}
				if (isValid) {
					var geo = Dituhui.latLonToMeters(new SuperMap.LonLat(x2, y2));
					// alert(geo);
					var geometry = new SuperMap.Geometry.Point(geo.lon, geo.lat);

					if (i == len - 1 && j == arr3.length - 1) {
						var car = new SuperMap.Feature.Vector(geometry.clone(),
							{
								// FEATUREID: f.id,
								// 根据节点生成时间
								TIME : 0
							}, styleCar1);
						cars.push(car);
					}

					lastGPSPoint = new Object();
					lastGPSPoint.x = x;
					lastGPSPoint.y = y;
					lastGPSPoint.gpsTime = gpsTime;

					path.push(geometry);
				}
			}
		}
	}
	var line = new SuperMap.Geometry.LineString(path);
	var lineFeature = new SuperMap.Feature.Vector(line, null, {
		strokeColor : '#0099ff',
		strokeOpacity : 1,
		strokeWidth : 5
	});
	layer_path.removeAllFeatures();
	layer_path.addFeatures(lineFeature);
	layer_path.addFeatures(cars);
	// layer_path_animator.addFeatures(cars);
	if (layer_path.getDataExtent().getWidth() > 0) {
		map.zoomToExtent(layer_path.getDataExtent());
	}
}

function caculateSpeed(x1, y1, t1, x2, y2, t2) {
	// 距离
	var deltaX = x1 - x2;
	//console.log("deltaX:" + distance)
	var deltaY = y1 - y2;
	//console.log("deltaY:" + deltaY)
	var distance = Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
	// 经纬度转换为公里
	distance = distance / 0.008983152841196329;
	// 时间
	var startTime = new Date(t1);
	var endTime = new Date(t2);
	// 小时
	var deltaTime = (endTime.getTime() - startTime.getTime()) / 1000 / 3600;
	// 速度
	var speed = distance / deltaTime;
	return speed;
}

function getDay(d) {
	var s = formatTime(d);
	return s;
}
// 格式化日期字符串
function formatTime(date) {
	var year = date.getFullYear()
	var month = date.getMonth() + 1
	if (month < 10) {
		month = "0" + month;
	}
	var day = date.getDate()
	if (day < 10) {
		day = "0" + day;
	}

	return year + "-" + month + "-" + day;
}

function getGPS() {
	var accountId = document.getElementById("accountId").value;
	if (accountId == "Test") {
		accountId = "李玮顾";
	}
	var startTime = document.getElementById("second_car_path_time_star").value;
	while (startTime.indexOf("-") != -1) {
		startTime = startTime.replace("-", "");
	}
	var endTime = document.getElementById("second_car_path_time_end").value;
	while (endTime.indexOf("-") != -1) {
		endTime = endTime.replace("-", "");
	}
	var url = 'http://gps.dituhui.com/wxweb/gps?a=' + accountId + '&start='
		+ startTime + '&end=' + endTime;
	$.ajax({
		type : 'GET',
		async : false,
		url : url,
		jsonp : 'callbacks',
		jsonpCallback : 'abc',
		dataType : 'jsonp',
		error : function(e) {
			alert("获取gps数据失败。url=" + url);
		},
		success : function(e) {
			// alert("success:" + e)
			/*
			 * if(e.result.data&&e.result.data.length <= 0){ alert('时间段内没有数据');
			 * TrackTable.clear(); $("#select-gpspoint-gather").html('0'); }
			 * else{ Map.searchPath(e); TrackTable.clear();
			 * TrackTable.display(); console.log(e); d = e; }
			 */
			//alert(e.data);
			Map.searchPath(e.data);

			getPic();
		}
	});
}

function getPic(){
	if(!viewPic){
		return;
	}
	var accountId = document.getElementById("accountId").value;
	if (accountId == "Test") {
		accountId = "李玮顾";
	}
	var startTime = document.getElementById("second_car_path_time_star").value;
	var endTime = document.getElementById("second_car_path_time_end").value;
	var url = 'http://gps.dituhui.com/wxweb/getimage?user='+accountId+'&day='+startTime
	$.ajax({
		type : 'GET',
		async : false,
		url : url,
		jsonp : 'callbacks',
		jsonpCallback : 'abc',
		dataType : 'jsonp',
		error : function(e) {
			alert("获取图片数据失败。url=" + url);
		},
		success : function(e) {
			//alert(e.data);
			var picData = e.data;
			map.removeAllPopup();
			picLayer.clearMarkers();
			$.each(picData,function(i,o){
				var coord = o.coord;
				var picName = o.imgNames;
				//alert(picName);
				var x = coord.split(",")[0];
				var y = coord.split(",")[1];
				var superMapPoint = new SuperMap.LonLat(x,y);
				var meterPoint=Dituhui.latLonToMeters(superMapPoint);
				// 初始化标记覆盖物类
				var size;
				if(isPC){
					size = new SuperMap.Size(22,16);
				}else{
					// 手机上需要设置大一点
					size = new SuperMap.Size(33,25);
				}
				var offset = new SuperMap.Pixel(-(size.w/2), -size.h);
				var icon = new SuperMap.Icon('theme/images/marker.png', size, offset);
				var marker = new SuperMap.Marker(new SuperMap.LonLat(meterPoint.lon, meterPoint.lat),icon);
				// 添加覆盖物到标记图层
				picLayer.addMarker(marker);
				//注册 click 事件,触发 mouseClickHandler()方法
				marker.events.on({"click":mouseClickHandler,
					"touchstart":mouseClickHandler //假如要在移动端的浏览器也实现点击弹框，则在注册touch类事件
				});
				//定义mouseClickHandler函数，触发click事件会调用此函数
				function mouseClickHandler(event){
					closeInfoWin();

					var contentHTML;
					if(isPC){
						contentHTML = "<div style='width:80px; font-size:12px;font-weight:bold ; opacity: 0.8'>"; 
					}else{
						// 手机上需要设置大一点
						contentHTML = "<div style='width:80px; font-size:24px;font-weight:bold ; opacity: 0.8'>"; 
					}
					//contentHTML += accountId;
					//contentHTML += "<br>";
					var picUrl = "http://gps.dituhui.com/wxweb/pic/"+picName+".png";
					//alert(picUrl);
					contentHTML += "<img src='"+picUrl+"' width='160px' height='160px' onclick='window.open(\""+picUrl+"\")'>";
					contentHTML += "</div>";
					//alert(marker.getLonLat());

					//初始化FramedCloud类
					var framedCloud = new SuperMap.Popup.FramedCloud(
						"chicken", 
						marker.getLonLat(),
						null,
						contentHTML,
						icon,
						true,
						null,
						true
					);

					infowin = framedCloud;
					map.addPopup(framedCloud);
				}
			})
		}
	});
}
var infowin = null;
function closeInfoWin(){
	if(infowin){
		try{
			infowin.hide();
			infowin.destroy();
		}
		catch(e){}
	}
}